<template>
	<view class="aus">
		<!-- 体检人员表单 -->
		<view class="add_list">
			<!-- 弹窗内容 -->
			<view class="v_div" v-if="!submissionOrNot">
				<view class="u_title" style="color: black;">体检人员录入</view>
				<view class="addDataBox">
					<view class="group">
						<text style="font-weight: 700; color: #444">站点名称: {{station_name}} </text>
						<!-- <picker mode="selector" :range="stationList" v-model="selectedStationIndex" range-key="account"
							@change="pickerChange">
							<input type="text" v-model="account" placeholder="请选择站点" />
						</picker> -->
					</view>
					<view class="group">
						<text class="required">姓名:</text>
						<input type="text" v-model="user.name" placeholder=" 请输入姓名" />
					</view>
					<view class="group">
						<text class="required">手机:</text>
						<input type="number" v-model="user.phone" placeholder=" 请输入联系方式" />
					</view>
					<radio-group ref="radioGroup" class="group" v-model="user.gender" @change="radioChange">
						<text class="required">性别:</text>
						<view class="radio-group">
							<label class="radio">
								<radio :checked="user.gender=='男'" value="男" />男
							</label>
							<label class="radio">
								<radio :checked="user.gender=='女'" value="女" />女
							</label>
						</view>
					</radio-group>
					<view class="group">
						<text class="required">年龄:</text>
						<input type="number" v-model="user.age" placeholder=" 请输入年龄" />
					</view>
					<view class="group">
						<text>身高:</text>
						<input type="number" v-model="user.height" placeholder=" 选填 : 请输入身高(cm)" />
					</view>
					<view class="group">
						<text>体重:</text>
						<input type="number" v-model="user.weight" placeholder=" 选填 : 请输入体重(kg)" />
					</view>
					<button type="primary" @tap="addDate"
						style="background-color:#1887be;width: 200px;margin-bottom: 20px">录入数据</button>
				</view>
			</view>
		</view>

		<!-- 二维码已失效页面 -->
		<view v-if="showQrInvalid" class="invalidModal">
			<view class="invalidContent">
				<view class="invalidPic"></view>
				<view class="invalidTextBox">
					<view class="invalidText">二维码已失效</view>
					<view class="invalidText">请咨询医生获取新的二维码。</view>
				</view>
			</view>
		</view>

		<!-- 链接已失效页面 -->
		<view v-if="showLinkInvalid" class="invalidModal">
			<view class="invalidContent">
				<view class="invalidPicLink"></view>
				<view class="invalidTextBox">
					<view class="invalidText">链接已失效</view>
					<view class="invalidText">请重新扫码获取表单链接。</view>
				</view>
			</view>
		</view>

		<!-- 提示信息 -->
		<view class="tip-container" v-show="showTip">
			<view class="tip-text">{{ tipMessage }}</view>
		</view>

		<!-- 提示信息弹窗 -->
		<popup-message ref="myPopup" :type="popupType" :message="popupMessage"></popup-message>

		<!-- 填写完成弹窗 -->
		<custom-message-popup ref="submitConfirm" icon="✔" message="感谢您的提交！" description="我们将尽快为您检测。" />
	</view>
</template>

<script>
	import {
		service
	} from '../../utils/service.js';
	import PopupMessage from '../components/PopupMessage.vue';
	import CustomMessagePopup from '../components/CustomMessagePopup.vue';

	export default {
		name: 'Home',
		components: {
			PopupMessage,
			CustomMessagePopup,
		},
		data() {
			return {
				uuid: null,
				account: '',
				// stationList: [], // 可选uuid列表
				user: {
					name: null,
					phone: null,
					gender: null,
					age: '',
					height: null,
					weight: null,
					created: null,
				},
				showTip: false,
				tipMessage: '',
				appid: 'wxccdaef60af53e540',
				appsecret: '883a1fb475a8f3141c1754110216a8f5',
				code: '',
				popupType: 'success',
				popupMessage: '默认提示信息',
				station_name: '', // 站点名
				qrCodeStr: '', // 二维码字符串
				submissionOrNot: true, // 是否提交表单
				showQrInvalid: false, // 二维码是否失效
				showLinkInvalid: false, // 链接是否失效
			}
		},
		onLoad() {
			let url = window.location.href;
			this.getSiteQr(url);
			this.refreshQrState();
			const code = uni.getStorageSync('code');
		},
		onHide() {},
		onShow() {},

		methods: {
			// 解析URL查询参数
			getUrlCode() {
				let fullUrl = window.location.href;
				let theRequest = new Object();
				if (fullUrl.indexOf("?") != -1) {
					var temp = fullUrl.split("?");
					let str = temp[1];
					let strs = str.split("&");
					for (var i = 0; i < strs.length; i++) {
						theRequest[strs[i].split("=")[0]] = strs[i].split("=")[1];
					}
				}
				return theRequest;
			},

			// 获得微信授权code
			getCode() {
				let local = window.location.href;
				let scope = "snsapi_base"; //静默授权 用户无感知
				this.code = this.getUrlCode().code;
				if (this.code == null || this.code === "") {
					window.location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${this.appid}&redirect_uri=${encodeURIComponent(
			          local
			        )}&response_type=code&scope=${scope}#wechat_redirect`
				} else {
					this.$store.commit('SET_CODE', this.code);
					console.log("无需跳转", this.code)
				}

			},

			// 获取站点id和二维码
			getSiteQr(url) {
				if (url.indexOf("?") != -1) {
					let str = url.substr(1);
					let strs = str.split("?")[1].split("&");
					let theRequest = new Object();
					for (var i = 0; i < strs.length; i++) {
						console.log(strs[i])
						theRequest[strs[i].split("=")[0]] = unescape(strs[i].split("=")[1]); // 使用 unescape 对值进行解码
					}
					let station_id = theRequest['id']
					let strParam = theRequest['str']
					this.uuid = station_id
					this.qrCodeStr = strParam
					this.$http.get(`/users/station_list/?station_id=` + station_id).then(res => {
						console.log(res.data)
						this.station_name = res.data.account
					});
				}
			},

			// 录入信息
			addDate() {
				this.$http.get(`/qr_strings/get_str/?random_str=${this.qrCodeStr}`).then(res => {
					this.qrCodeState = res.data.state;
					console.log("hshhs当前状态", this.qrCodeState)
					if (this.qrCodeState === 1) {
						if (this.validateFormData()) {
							let formData = this.createFormData();
							this.submitFormData(formData);
							// 修改二维码状态为已填写信息
							let qrStateForm = new FormData();
							qrStateForm.append("random_str", this.qrCodeStr);
							qrStateForm.append("state", 2);
							this.changeQrCode(qrStateForm);
						}
					} else if (this.qrCodeState === -1) {
						this.invalidQrCode();
					}
				})
			},

			// 获取二维码状态
			refreshQrState() {
				this.$http.get(`/qr_strings/get_str/?random_str=${this.qrCodeStr}`).then(res => {
					this.qrCodeState = res.data.state;
					console.log("当前状态: ", this.qrCodeState);
					// 二维码已失效
					if (this.qrCodeState === -1) {
						this.invalidQrCode();
					}
					// 二维码已填写
					else if (this.qrCodeState === 2) {
						this.invalidLink();
					} 
					else {
						this.submissionOrNot = false;
						this.getCode();
					}
				})
			},


			// 验证全部数据
			validateFormData() {
				if (!this.validateStationId() || !this.validateName() || !this.validatePhone() ||
					!this.validateGender() || !this.validateAge() || !this.validateHeight() ||
					!this.validateWeight()) {
					return false;
				}
				return true;
			},

			// 验证站点
			validateStationId() {
				if (this.uuid === null) {
					this.showTipMessage('请填写站点信息');
					return false;
				}
				return true;
			},

			// 验证姓名
			validateName() {
				if (this.user.name === null || this.user.name.length < 2) {
					this.showTipMessage('请填写有效的中文英文姓名');
					return false;
				}
				return true;
			},

			// 验证电话
			validatePhone() {
				const phoneRegex = /^1\d{10}$/;
				if (!phoneRegex.test(this.user.phone)) {
					this.showTipMessage('请填写有效的中国手机号码');
					return false;
				}
				return true;
			},

			// 验证性别
			validateGender() {
				const genderRegex = /^(男|女)$/;
				if (!genderRegex.test(this.user.gender)) {
					this.showTipMessage('请填写有效的性别（男或女）');
					return false;
				}
				return true;
			},

			// 验证年龄
			validateAge() {
				const age = parseInt(this.user.age);
				if (isNaN(age) || age <= 0 || age >= 150) {
					this.showTipMessage('请填写有效的年龄');
					return false;
				}
				return true;
			},

			// 验证身高
			validateHeight() {
				const height = parseInt(this.user.height);
				if (height <= 0 || height >= 250) {
					this.showTipMessage('请填写有效的身高');
					return false;
				}
				return true;
			},

			// 验证体重
			validateWeight() {
				const weight = parseInt(this.user.weight);
				if (weight <= 0 || weight >= 200) {
					this.showTipMessage('请填写有效的体重');
					return false;
				}
				return true;
			},

			// 构建提交表单信息
			createFormData() {
				let formData = new FormData();
				formData.append("code", this.code);
				formData.append("station_key", this.uuid);
				formData.append("patient_name", this.user.name);
				formData.append("patient_age", this.user.age);
				formData.append("patient_gender", this.user.gender);
				formData.append("patient_phone", this.user.phone);
				formData.append("patient_height", this.user.height || 0);
				formData.append("patient_weight", this.user.weight || 0);
				return formData;
			},

			// 初始化数据
			initFormData() {
				this.user.name = null;
				this.user.age = '';
				this.user.gender = null;
				this.user.phone = null;
				this.user.height = null;
				this.user.weight = null;
			},

			// 提交表单
			submitFormData(formData) {
				service.post('/patients/collect_info/', formData).then(res => {
					this.showSuccessMessage();
					this.$refs.submitConfirm.open();
					this.initFormData();
					this.submissionOrNot = true;
				}).catch(error => {
					this.showFailureMessage();
				});
			},

			// 修改二维码状态
			changeQrCode(qrStateForm) {
				service.post('/qr_strings/update_str/', qrStateForm).then(res => {
					console.log("修改成功")
				}).catch(error => {
					console.log("修改失败")
				});
			},

			// 二维码已失效
			invalidQrCode() {
				this.submissionOrNot = true;
				this.showQrInvalid = true;
			},

			// 链接已失效
			invalidLink() {
				this.submissionOrNot = true;
				this.showLinkInvalid = true;
			},

			// 添加成功
			showSuccessMessage() {
				this.popupType = 'success';
				this.popupMessage = '添加成功！';
				this.$refs.myPopup.open();
			},

			// 添加失败
			showFailureMessage() {
				this.popupType = 'error';
				this.popupMessage = '添加失败！';
				this.$refs.myPopup.open();
			},

			// 显示提示信息
			showTipMessage(message) {
				this.showTip = true;
				this.tipMessage = message;
				setTimeout(() => {
					this.showTip = false;
				}, 3000);
			},

			//获取选中状态
			change(e) {
				this.selectArr = e.detail;
			},

			// 男女单选选择器
			radioChange(e) {
				this.user.gender = e.detail.value;
			},

			// 选择站点
			// pickerChange(e) {
			// 	const selectedStationIndex = e.detail.value;
			// 	const selectedStation = this.stationList[selectedStationIndex];
			// 	console.log(selectedStation);
			// 	this.uuid = selectedStation.id;
			// 	this.account = selectedStation.account;
			// 	console.log(this.uuid, this.account)
			// },
		}
	}
</script>

<style lang='less' scoped>
	/deep/.uni-dialog-title-text {
		size: 80rpx;
		font-weight: bold;
		color: black;
	}

	/deep/.uni-dialog-content {
		text-align: center;
		color: #90908a;
		size: 30rpx;
	}

	/deep/.uni-dialog-button {
		color: #3d7dff !important;
		cursor: pointer;
	}

	.aus {
		width: 100%;

		display: flex;
		flex-direction: column;

		/* 提示信息容器的样式 */
		.tip-container {
			position: fixed;
			top: 15%;
			left: 50%;
			transform: translate(-50%, -50%);
			background-color: rgba(0, 0, 0, 0.7);
			padding: 10px;
			border-radius: 8px;
			color: #fff;
			z-index: 9999;
		}

		/* 提示信息文本的样式*/
		.tip-text {
			font-size: 18px;
			color: #fff;
		}

		/* 添加人员表样式 */
		.add_list {
			position: absolute;
			left: 0;
			top: 0;
			display: flex;
			justify-content: center;
			align-items: center;
			width: 100%;
			height: 100%;
			overflow-x: hidden;
			background-color: rgba(0, 0, 0, .29803922);
			border: none;
			border-radius: 0;
			box-shadow: none;
			transition: .5s;
		}

		.v_div {
			display: flex;
			flex-direction: column;
			align-self: center;
			width: 330px;
			/* height: 300px; */
			background-color: rgba(255, 255, 255, 1);
			border-radius: 10rpx;
			box-shadow: none;
			font-family: '微软雅黑', sans-serif;
			font-weight: 400;
			font-style: normal;
			color: rgba(153, 153, 153, 0.9450980392156862);

			.colse {
				width: 36rpx;
				height: 12rpx;
			}

			.u_title {
				margin-top: 40rpx;
				text-align: center;
				font-family: '微软雅黑', sans-serif;
				font-weight: 600;
				font-style: normal;
				font-size: 40rpx;
				color: rgba(153, 153, 153, 0.9450980392156862);
			}

			// 录入表单样式
			.addDataBox {
				background-color: #fff;
				color: #000;

				.group {
					padding: 5px;
					border-radius: 20upx;
					margin: 20rpx auto;
					display: flex;
					justify-content: center;
					align-items: center;

					//必填项
					.required::before {
						content: '*';
						color: red;
					}

					button {
						margin-left: 50rpx;
						width: 10px;
					}

					.radio-group {
						display: flex;
						align-items: center;
						justify-content: space-between;
					}

					.radio {
						padding: 0 50rpx;
					}

					input {
						/* width: 170upx; */
						height: 60upx;
						border: 1upx solid #eee;
						margin-left: 10rpx;
					}
				}
			}
		}

		/* 二维码失效 */
		.invalidModal {
			position: fixed;
			top: 0;
			left: 0;
			right: 0;
			bottom: 0;
			background-color: rgba(0, 0, 0, 0.5);
			display: flex;
			justify-content: center;
			align-items: center;
			z-index: 10000;
		}

		.invalidContent {
			padding: 20rpx;
			border-radius: 10rpx;
			height: 550rpx;
			width: 550rpx;
			background: #fff;
			position: relative;
			display: flex;
			justify-content: center;
			align-items: center;
		}

		/* 二维码失效 */
		.invalidPic {
			position: absolute;
			background: url('../../static/QRinvalid.png') no-repeat;
			background-size: contain;
			top: 90rpx;
			height: 216rpx;
			width: 226rpx;
		}

		/* 链接失效 */
		.invalidPicLink {
			position: absolute;
			background: url('../../static/LinkInvalid.png') no-repeat;
			background-size: contain;
			top: 90rpx;
			height: 216rpx;
			width: 226rpx;
		}

		.invalidTextBox {
			position: absolute;
			top: 60%;
			display: flex;
			width: 80%;
			flex-direction: column;
		}

		.invalidText {
			margin: 10rpx auto;
			font-size: 30rpx;
			font-weight: bold;
			color: #333;
		}


		@media screen and (max-width: 900px) {
			.v_div {
				width: 80%;
				margin-bottom: 30%;
			}

			.u_title {
				font-size: 40rpx;
			}

			.invalidContent {
				padding: 10rpx;
				height: 500rpx;
				width: 500rpx;
			}

			.invalidText {
				font-size: 23rpx;
			}
		}
	}
</style>